// https://leetcode.cn/problems/fraction-to-recurring-decimal/
// Created by ade on 2022/8/24.
//
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        int minusFlag = 0;
        if (numerator < 0 ^ denominator < 0) minusFlag = 1;
        long long n = numerator;
        long long d = denominator;
        if (n % d == 0) {
            return to_string(n / d);
        }
        n = abs(n);
        d = abs(d);

        int z = n / d; // 整数部分
        long long f = n % d;
        string zx = ""; // 小数
        vector<int> fst = {};
        if (f < d) {
            fst.push_back(f);
            while (f < d) {
                f *= 10;
                if (f < d) {
                    fst.push_back(f);
                    zx += '0';
                }
            }
        }
        int flag = 0; // 循环小数标志
        int diff = 0; // 循环的长度
        while (f > 0) {
            zx += f / d + '0';
            if (f % d == 0) {
                break;
            } else {
                f %= d;
                if (fst.empty()) {
                    fst.push_back(f);
                    f *= 10;
                    continue;
                }
                for (int i = fst.size() - 1; i >= 0; i--) {
                    if (fst[i] == f) {
                        flag = 1;
                        diff = fst.size() - i;
                        break;
                    }
                }
                if (flag == 0) {
                    fst.push_back(f);
                    f *= 10;
                } else {
                    break;
                }
            }
        }
        string res = to_string(z) + "." + zx;
        if (flag > 0) {
            res.insert(res.begin() + res.size() - diff, '(');
            res += ')';
        }
        if (minusFlag) res = "-" + res;
        return res;
    }
};

int main() {
    Solution so;
    cout << so.fractionToDecimal(4, 333) << endl;
    return 0;
}